import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeft, Bell, Clock, Volume2, Smartphone, Mail, AlertCircle, Wifi, WifiOff } from 'lucide-react';
import NotificationService from '../services/notificationService';
import { notificationAPI, NotificationSettings as APINotificationSettings } from '../services/notificationAPI';
import PWANotificationService from '../services/pwaNotificationService';


export default function NotificationPage() {
  const navigate = useNavigate();
  const [settings, setSettings] = useState<APINotificationSettings>({
    task_reminders: true,
    daily_summary: true,
    weekly_review: true,
    overdue_alerts: true,
    reminder_time: '09:00',
    sound_enabled: true,
    vibration_enabled: true,
    email_notifications: false
  });
  
  const [permission, setPermission] = useState<NotificationPermission>('default');
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [showTestResult, setShowTestResult] = useState<string | null>(null);
  
  // PWA推送通知状态
  const [pwaService] = useState(() => PWANotificationService.getInstance());
  const [pwaStatus, setPwaStatus] = useState({
    supported: false,
    subscribed: false,
    permission: 'default' as NotificationPermission
  });

  const legacyNotificationService = NotificationService.getInstance();

  useEffect(() => {
    loadSettings();
    checkPermission();
    checkPwaStatus();
  }, []);

  const checkPwaStatus = async () => {
    try {
      const status = await pwaService.getSubscriptionStatus();
      setPwaStatus(status);
    } catch (error) {
      console.error('检查PWA状态失败:', error);
    }
  };

  const handlePwaSubscription = async () => {
    try {
      if (pwaStatus.subscribed) {
        await pwaService.unsubscribeFromPushNotifications();
      } else {
        await pwaService.subscribeToPushNotifications();
      }
      await checkPwaStatus();
    } catch (error) {
      console.error('PWA订阅操作失败:', error);
      setShowTestResult('PWA推送操作失败: ' + (error as Error).message);
      setTimeout(() => setShowTestResult(null), 3000);
    }
  };

  const loadSettings = async () => {
    try {
      setIsLoading(true);
      const serverSettings = await notificationAPI.getSettings();
      setSettings(serverSettings);
    } catch (error) {
      console.error('加载通知设置失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const checkPermission = () => {
    const currentPermission = legacyNotificationService.getPermissionStatus();
    setPermission(currentPermission);
  };

  const handleSettingChange = async (key: keyof APINotificationSettings, value: any) => {
    const oldSettings = { ...settings };
    const newSettings = { ...settings, [key]: value };
    setSettings(newSettings);

    try {
      setIsSaving(true);
      const updatedSettings = await notificationAPI.updateSettings({ [key]: value });
      
      // 使用服务器返回的最新设置更新本地状态
      setSettings(updatedSettings);
      
      // 同时更新本地Service Worker设置
      legacyNotificationService.saveSettings({ [key]: value });
      
    } catch (error) {
      console.error('保存设置失败:', error);
      // 回滚设置到修改前的状态
      setSettings(oldSettings);
      
      // 显示错误提示
      setShowTestResult('保存设置失败: ' + (error as Error).message);
      setTimeout(() => setShowTestResult(null), 3000);
    } finally {
      setIsSaving(false);
    }
  };

  const handleRequestPermission = async () => {
    try {
      const newPermission = await legacyNotificationService.requestPermission();
      setPermission(newPermission);
      
      if (newPermission === 'granted') {
        setShowTestResult('通知权限已授予！');
      } else {
        setShowTestResult('通知权限被拒绝，请在浏览器设置中手动开启');
      }
    } catch (error) {
      console.error('请求通知权限失败:', error);
      setShowTestResult('请求权限时发生错误');
    }
    
    setTimeout(() => setShowTestResult(null), 3000);
  };

  const handleTestNotification = async () => {
    try {
      await legacyNotificationService.testNotification();
      setShowTestResult('测试通知已发送！');
    } catch (error) {
      console.error('发送测试通知失败:', error);
      setShowTestResult('发送测试通知失败，请检查权限设置');
    }
    
    setTimeout(() => setShowTestResult(null), 3000);
  };

  const handleTestPwaNotification = async () => {
    try {
      await pwaService.sendTestNotification();
      setShowTestResult('PWA测试推送已发送！');
    } catch (error) {
      console.error('发送PWA测试通知失败:', error);
      setShowTestResult('PWA推送测试失败: ' + (error as Error).message);
    }
    
    setTimeout(() => setShowTestResult(null), 3000);
  };

  const getPermissionStatusInfo = () => {
    switch (permission) {
      case 'granted':
        return { 
          text: '已授权', 
          color: 'text-green-600 bg-green-50 border-green-200', 
          icon: Bell 
        };
      case 'denied':
        return { 
          text: '已拒绝', 
          color: 'text-red-600 bg-red-50 border-red-200', 
          icon: AlertCircle 
        };
      default:
        return { 
          text: '未设置', 
          color: 'text-yellow-600 bg-yellow-50 border-yellow-200', 
          icon: Clock 
        };
    }
  };

  const permissionInfo = getPermissionStatusInfo();
  const PermissionIcon = permissionInfo.icon;

  if (isLoading) {
    return (
      <div className="min-h-screen bg-theme-bg-secondary">
        <header className="sticky top-0 bg-theme-bg/95 backdrop-blur-sm shadow-sm border-b border-theme-border/60 z-10">
          <div className="flex items-center justify-between px-4 py-3 max-w-md mx-auto">
            <button
              onClick={() => navigate(-1)}
              className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all"
            >
              <ArrowLeft size={20} />
            </button>
            <h1 className="text-lg font-semibold text-theme-text">通知设置</h1>
            <div className="w-9 h-9" />
          </div>
        </header>

        <main className="px-4 py-6 max-w-md mx-auto">
          <div className="space-y-4">
            {[1, 2, 3, 4, 5].map(i => (
              <div key={i} className="bg-theme-bg rounded-xl p-4 animate-pulse">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className="w-8 h-8 bg-slate-200 rounded-lg"></div>
                    <div>
                      <div className="w-24 h-4 bg-slate-200 rounded mb-2"></div>
                      <div className="w-32 h-3 bg-slate-200 rounded"></div>
                    </div>
                  </div>
                  <div className="w-11 h-6 bg-slate-200 rounded-full"></div>
                </div>
              </div>
            ))}
          </div>
        </main>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-theme-bg-secondary">
      {/* Header */}
      <header className="sticky top-0 bg-theme-bg/95 backdrop-blur-sm shadow-sm border-b border-theme-border/60 z-10">
        <div className="flex items-center justify-between px-4 py-3 max-w-md mx-auto">
          <button
            onClick={() => navigate('/profile')}
            className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all touch-manipulation"
          >
            <ArrowLeft size={20} />
          </button>
          <h1 className="text-lg font-semibold text-theme-text">通知设置</h1>
          <div className="w-9 h-9" /> {/* 占位符保持居中 */}
        </div>
      </header>

      <main className="px-4 py-6 space-y-4 max-w-md mx-auto">
        {/* 权限状态卡片 */}
        <div className={`bg-theme-bg rounded-xl border p-4 ${permissionInfo.color}`}>
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-3">
              <PermissionIcon size={24} />
              <div>
                <h3 className="font-semibold">通知权限</h3>
                <p className="text-sm opacity-80">状态: {permissionInfo.text}</p>
              </div>
            </div>
          </div>

          <div className="flex gap-2">
            {permission !== 'granted' && (
              <button
                onClick={handleRequestPermission}
                className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 
                         transition-colors text-sm font-medium"
              >
                授权通知
              </button>
            )}
            
            {permission === 'granted' && (
              <button
                onClick={handleTestNotification}
                className="flex-1 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 
                         transition-colors text-sm font-medium"
              >
                测试通知
              </button>
            )}
          </div>

          {showTestResult && (
            <div className="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-lg">
              <p className="text-sm text-blue-700">{showTestResult}</p>
            </div>
          )}
        </div>

        {/* 通知类型设置 */}
        <div className="bg-theme-bg rounded-xl border border-theme-border/60 shadow-sm overflow-hidden">
          <div className="p-4 border-b border-slate-100">
            <h3 className="font-semibold text-theme-text">通知类型</h3>
            <p className="text-sm text-theme-text-muted mt-1">选择您希望接收的通知类型</p>
          </div>

          <div className="space-y-0">
            <div className="flex items-center justify-between p-4 border-b border-slate-100">
              <div className="flex items-center gap-3">
                <Clock size={20} className="text-blue-600" />
                <div>
                  <span className="font-medium text-theme-text">任务提醒</span>
                  <p className="text-sm text-theme-text-muted">任务即将到期时提醒</p>
                </div>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={settings.task_reminders}
                  onChange={(e) => handleSettingChange('task_reminders', e.target.checked)}
                  disabled={isSaving}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-4 
                              peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full 
                              peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] 
                              after:left-[2px] after:bg-theme-bg after:border-theme-border after:border after:rounded-full 
                              after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600 
                              peer-disabled:opacity-50"></div>
              </label>
            </div>

            <div className="flex items-center justify-between p-4 border-b border-slate-100">
              <div className="flex items-center gap-3">
                <AlertCircle size={20} className="text-red-600" />
                <div>
                  <span className="font-medium text-theme-text">逾期提醒</span>
                  <p className="text-sm text-theme-text-muted">任务逾期时通知</p>
                </div>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={settings.overdue_alerts}
                  onChange={(e) => handleSettingChange('overdue_alerts', e.target.checked)}
                  disabled={isSaving}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-4 
                              peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full 
                              peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] 
                              after:left-[2px] after:bg-theme-bg after:border-theme-border after:border after:rounded-full 
                              after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600 
                              peer-disabled:opacity-50"></div>
              </label>
            </div>

            <div className="flex items-center justify-between p-4 border-b border-slate-100">
              <div className="flex items-center gap-3">
                <Bell size={20} className="text-green-600" />
                <div>
                  <span className="font-medium text-theme-text">每日总结</span>
                  <p className="text-sm text-theme-text-muted">每日工作总结通知</p>
                </div>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={settings.daily_summary}
                  onChange={(e) => handleSettingChange('daily_summary', e.target.checked)}
                  disabled={isSaving}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-4 
                              peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full 
                              peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] 
                              after:left-[2px] after:bg-theme-bg after:border-theme-border after:border after:rounded-full 
                              after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600 
                              peer-disabled:opacity-50"></div>
              </label>
            </div>

            <div className="flex items-center justify-between p-4">
              <div className="flex items-center gap-3">
                <Mail size={20} className="text-purple-600" />
                <div>
                  <span className="font-medium text-theme-text">邮件通知</span>
                  <p className="text-sm text-theme-text-muted">通过邮件接收通知</p>
                </div>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={settings.email_notifications}
                  onChange={(e) => handleSettingChange('email_notifications', e.target.checked)}
                  disabled={isSaving}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-4 
                              peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full 
                              peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] 
                              after:left-[2px] after:bg-theme-bg after:border-theme-border after:border after:rounded-full 
                              after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600 
                              peer-disabled:opacity-50"></div>
              </label>
            </div>
          </div>
        </div>

        {/* 提醒时间设置 */}
        <div className="bg-theme-bg rounded-xl border border-theme-border/60 shadow-sm p-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Clock size={20} className="text-blue-600" />
              <div>
                <h3 className="font-semibold text-theme-text">每日总结时间</h3>
                <p className="text-sm text-theme-text-muted">设置每日总结通知的时间</p>
              </div>
            </div>
            <input
              type="time"
              value={settings.reminder_time}
              onChange={(e) => handleSettingChange('reminder_time', e.target.value)}
              disabled={isSaving || !settings.daily_summary}
              className="px-3 py-2 border border-theme-border rounded-lg focus:outline-none 
                       focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed
                       text-sm"
            />
          </div>
        </div>

        {/* PWA推送通知设置 */}
        <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl border border-blue-200 shadow-sm p-4">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-3">
              {pwaStatus.subscribed ? (
                <Wifi size={20} className="text-green-600" />
              ) : (
                <WifiOff size={20} className="text-gray-400" />
              )}
              <div>
                <h3 className="font-semibold text-blue-900">PWA推送通知</h3>
                <p className="text-sm text-blue-700">
                  {pwaStatus.supported 
                    ? (pwaStatus.subscribed ? '已启用 - 支持后台推送' : '未启用 - 支持后台推送')
                    : '浏览器不支持PWA推送通知'
                  }
                </p>
              </div>
            </div>
            <span className={`text-xs px-2 py-1 rounded-full ${
              pwaStatus.subscribed 
                ? 'bg-green-100 text-green-700' 
                : 'bg-gray-100 text-gray-600'
            }`}>
              {pwaStatus.subscribed ? '已启用' : '未启用'}
            </span>
          </div>
          
          <div className="space-y-3">
            <div className="flex gap-2">
              {pwaStatus.supported && (
                <>
                  <button 
                    onClick={handlePwaSubscription}
                    disabled={permission !== 'granted'}
                    className={`flex-1 px-3 py-2 text-sm rounded transition-colors ${
                      pwaStatus.subscribed 
                        ? 'bg-red-600 text-white hover:bg-red-700' 
                        : 'bg-blue-600 text-white hover:bg-blue-700'
                    } disabled:bg-gray-300 disabled:cursor-not-allowed`}
                  >
                    {pwaStatus.subscribed ? '禁用PWA推送' : '启用PWA推送'}
                  </button>
                  
                  {/* 重试按钮（当订阅失败时显示） */}
                  {!pwaStatus.subscribed && (
                    <button 
                      onClick={async () => {
                        try {
                          // 强制重新诊断和重试
                          console.log('🔄 用户手动重试PWA推送订阅...');
                          await pwaService.subscribeToPushNotifications();
                          await checkPwaStatus();
                          setShowTestResult('重试成功！PWA推送已启用');
                        } catch (error) {
                          console.error('重试失败:', error);
                          setShowTestResult('重试失败: ' + (error as Error).message);
                        }
                        setTimeout(() => setShowTestResult(null), 5000);
                      }}
                      className="px-3 py-2 text-sm bg-orange-600 text-white rounded hover:bg-orange-700"
                    >
                      重试
                    </button>
                  )}
                </>
              )}
              
              {pwaStatus.subscribed && (
                <button 
                  onClick={handleTestPwaNotification}
                  className="px-3 py-2 text-sm bg-green-600 text-white rounded hover:bg-green-700"
                >
                  测试PWA推送
                </button>
              )}
            </div>
            
            <div className="text-xs text-blue-600 space-y-1">
              <p>✅ 后台推送通知 - 应用关闭时也能接收</p>
              <p>✅ 系统级通知显示</p>
              <p>✅ 离线消息缓存</p>
              {(window.location.hostname === 'localhost' && window.location.protocol === 'http:') && (
                <p className="text-yellow-600">⚠️ 本地开发环境可能无法正常使用</p>
              )}
            </div>
            
            {/* 网络连接问题提示 */}
            {!pwaStatus.subscribed && (
              <div className="text-xs text-amber-700 bg-amber-50 p-3 rounded-lg border border-amber-200">
                <p className="font-medium mb-2">⚠️ PWA推送通知可能受网络环境影响</p>
                <div className="space-y-1">
                  <p>• 需要连接到推送服务（如Google FCM）</p>
                  <p>• 防火墙或网络代理可能阻止连接</p>
                  <p>• 如果无法启用，基础通知功能仍然可用</p>
                </div>
                <div className="mt-2 text-xs">
                  <p className="font-medium">替代方案：</p>
                  <p>• 使用上方的基础浏览器通知</p>
                  <p>• 启用邮件通知提醒</p>
                  <p>• 定期检查应用中的任务状态</p>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* 声音和震动设置 */}
        <div className="bg-theme-bg rounded-xl border border-theme-border/60 shadow-sm overflow-hidden">
          <div className="p-4 border-b border-slate-100">
            <h3 className="font-semibold text-theme-text">通知效果</h3>
            <p className="text-sm text-theme-text-muted mt-1">自定义通知的声音和震动效果</p>
          </div>

          <div className="space-y-0">
            <div className="flex items-center justify-between p-4 border-b border-slate-100">
              <div className="flex items-center gap-3">
                <Volume2 size={20} className="text-green-600" />
                <span className="font-medium text-theme-text">声音提醒</span>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={settings.sound_enabled}
                  onChange={(e) => handleSettingChange('sound_enabled', e.target.checked)}
                  disabled={isSaving}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-4 
                              peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full 
                              peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] 
                              after:left-[2px] after:bg-theme-bg after:border-theme-border after:border after:rounded-full 
                              after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600 
                              peer-disabled:opacity-50"></div>
              </label>
            </div>

            <div className="flex items-center justify-between p-4">
              <div className="flex items-center gap-3">
                <Smartphone size={20} className="text-orange-600" />
                <span className="font-medium text-theme-text">震动提醒</span>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={settings.vibration_enabled}
                  onChange={(e) => handleSettingChange('vibration_enabled', e.target.checked)}
                  disabled={isSaving}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-4 
                              peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full 
                              peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] 
                              after:left-[2px] after:bg-theme-bg after:border-theme-border after:border after:rounded-full 
                              after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600 
                              peer-disabled:opacity-50"></div>
              </label>
            </div>
          </div>
        </div>

        {/* 说明信息 */}
        <div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
          <h4 className="font-semibold text-blue-800 mb-2">使用说明</h4>
          <ul className="text-sm text-blue-700 space-y-1">
            <li>• 任务提醒会在任务到期前30分钟发送</li>
            <li>• 每日总结会在设定时间自动发送</li>
            <li>• 逾期提醒会在任务逾期时立即发送</li>
            <li>• 关闭浏览器后，部分通知可能无法正常发送</li>
          </ul>
        </div>

        {/* 保存状态指示器 */}
        {isSaving && (
          <div className="fixed bottom-4 left-1/2 transform -translate-x-1/2 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg">
            正在保存设置...
          </div>
        )}
      </main>
    </div>
  );
}
